package com.wenhai.concurrency.aqs;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;

/**
 * @ClassName NonReentrantLockDemo
 * @Description
 * @Author 谢文海
 * @Date 2021/4/17 0:12
 * @Version 1.0
 **/
public class NonReentrantLockDemo {
    final static NonReentrantLock lock = new NonReentrantLock();
    final static Condition notFull = lock.newCondition();
    final static Condition notEmpty = lock.newCondition();
    final static Queue<String> queue = new LinkedBlockingQueue<>();
    final static int queueSize = 10;

    public static void main(String[] args) throws InterruptedException {
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {
                    while (queue.size() == queueSize) {
                        notEmpty.await();
                    }
                    queue.add("当前时间：" + System.nanoTime());
                    notFull.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();

                } finally {
                    lock.unlock();
                }
            }
        });

        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lock.lock();
                try {

                    while (queue.isEmpty()) {
                        notFull.await();
                    }
                    System.out.println("队列出队元素为：" + queue.poll());
                    notEmpty.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });


        producer.start();
        consumer.start();
    }
}
